package com.lq.memo.service.impl;

import com.lq.memo.entity.User;
import com.lq.memo.mapper.UserMapper;
import com.lq.memo.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: memo
 * @description:
 * @author: LQ
 * @create: 2021-11-05 11:15
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    JdbcTemplate template;

    @Autowired
    UserMapper userMapper;

    @Override
    public List<User> getAllUser() {
        String sql = "select * from user ";
        List<User> userList = template.query(sql, new BeanPropertyRowMapper<User>(User.class));
        return userList;
    }

    @Override
    public User getUser(User user) {
        String sql = "select * from user  where 1 = 1 ";
        List<Object> queryParmList = new ArrayList<>();
        if (StringUtils.isNotBlank(user.getMobile())) {
            sql += " and mobile = ? ";
            queryParmList.add(user.getMobile());
        }
        if (user.getId() != null) {
            sql += " and id = ? ";
            queryParmList.add(user.getId());
        }
        if (StringUtils.isNotBlank(user.getEmail())) {
            sql += " and email = ? ";
            queryParmList.add(user.getEmail());
        }
        if (StringUtils.isNotBlank(user.getOpenId())) {
            sql += " and openId = ? ";
            queryParmList.add(user.getOpenId());
        }
        List<User> userList = template.query(sql, new BeanPropertyRowMapper<User>(User.class), queryParmList.toArray());
        if (userList.size() > 0) {
            return userList.get(0);
        }
        return null;
    }

    @Override
    public int saveUser(User user) {
        int insert = userMapper.insert(user);
        return insert;
    }

}
